package server

import (
	core "carmanager/db"
	model "carmanager/models"
	"carmanager/models/dto"
	"carmanager/util"
	"fmt"
	"time"
)

type LoginService struct{}

func (login *LoginService) Login(admin string, password string) (bool, dto.TokenDto) {
	db := core.GetDB()
	users := model.User{}
	db.Where("userName=? and passWord=?", admin, util.EncryMd5(password)).First(&users)
	if (users == model.User{}) {

		return false, dto.TokenDto{}
	}
	error, token := util.GenToken(&users)
	if error != nil {
		fmt.Println(error)
		return false, dto.TokenDto{}
	}
	Role := new(model.Role)
	db.Where("roleid", users.Roleid).Find(Role)
	return true, dto.TokenDto{UserId: users.ID, Token: token, RoleName: Role.RoleName, NickName: users.NickName, UserName: users.UserName}
}
func (login *LoginService) AddUser(u model.User) bool {
	db := core.GetDB()
	users := model.User{}
	db.Where("userName=?", u.UserName).First(&users)
	if (users != model.User{}) {
		return false
	}
	u.PassWord = util.EncryMd5(u.PassWord)
	u.Datetime = time.Now()
	db.Save(&u)
	return true
}
